import org.apache.commons.mail.HtmlEmail;
import org.codehaus.groovy.grails.commons.ApplicationHolder

class AuthEmailService {

    private Session getSession() {
        def grailsApplication = ApplicationHolder.application
 
        Properties mailProps =
            grailsApplication.config.mail?.toProperties("mail")
        if (!mailProps) {
            mailProps = new Properties()
        }

        return Session.getDefaultInstance(mailProps)
    }

    /**
     * Send a mail using Commons HtmlEmail and the configured settings.
     */
    def sendMail(String from, String to, String subject, String message) {
        def grailsApplication = ApplicationHolder.application

        HtmlEmail email = new HtmlEmail();
        email.setMailSession(getSession());
        
        // If a username is configured, then setup authentication
        if (grailsApplication.config.authorize.smtp?.username) {
            def username = grailsApplication.config.authorize.smtp?.username
            def password = grailsApplication.config.authorize.smtp?.password
            email.setAuthentication(username, password)
        }
        // If a pop3 host is configured, the user needs POP-before-SMTP authentication
        if (grailsApplication.config.authorize.pop?.host) {
            def host = grailsApplication.config.authorize.pop?.host
            def username = grailsApplication.config.authorize.pop?.username
            def password = grailsApplication.config.authorize.pop?.password
            email.setPopBeforeSmtp(true, host, username, password)
        }
        email.setFrom(from, from);
        email.addTo(to);
        email.setSubject(subject);
        email.setHtmlMsg(message);
        email.send();
    }
}